package com.iotproject.studyservice.controller;


import com.iotproject.commonutils.R;
import com.iotproject.studyservice.entity.StudyReading;
import com.iotproject.studyservice.service.StudyReadingService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 书籍 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2023-04-09
 */
@RestController
@RequestMapping("/studyservice/study-reading")
public class StudyReadingController {

    @Autowired
    StudyReadingService studyReadingService;

    //插入数据
    @PostMapping("insertBook")
    public R insertBook(@RequestBody StudyReading studyReading) {
        StudyReading insertStudyReading = new StudyReading();
        insertStudyReading.setName(studyReading.getName());
        insertStudyReading.setAuthor(studyReading.getAuthor());
        insertStudyReading.setCover(studyReading.getCover());
        insertStudyReading.setDescription(studyReading.getDescription());
        insertStudyReading.setContent(studyReading.getContent());
        boolean save = studyReadingService.save(insertStudyReading);
        if (save) {
            return R.ok();
        }
        return R.error();
    }

    //查找所有书籍
    @GetMapping("getBookList")
    public R getBookList() {
        List<StudyReading> list = studyReadingService.list(null);
        return R.ok().data("list", list);
    }

    //条件过滤(书籍或作者)查找书籍
    @GetMapping("searchBook/{keywords}")
    public R searchBook(@PathVariable("keywords") String keywords) {
        QueryWrapper<StudyReading> studyReadingQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(keywords)) {
            studyReadingQueryWrapper.like("name", keywords).or().like("author", keywords);
        }
        List<StudyReading> list = studyReadingService.list(studyReadingQueryWrapper);
        return R.ok().data("list", list); //list可能为null
    }

    //根据书籍id获取书籍信息
    @GetMapping("getBookById/{bookId}")
    public R getBookById(@PathVariable("bookId") String bookId) {
        StudyReading book = studyReadingService.getById(bookId);
        return R.ok().data("book", book);
    }

}

